package com.wzy.netrequestframework;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

import jsonParser.SpecialListParser;
import jsonParser.jsonData.ErrorData;
import jsonParser.jsonData.SpecialItem;
import network.NetConnectTask;
import network.RequestParams;
import network.RequestUrl;
import network.TaskExecute;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private Button btn;
    private TextView mText;
    private NetConnectTask mNetTask;
    private SpecialListParser mJsonParser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.click);
        mText = (TextView) findViewById(R.id.text);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        loadNetData();
    }

    /**
     * 加载网络数据
     */
    private void loadNetData() {

        if (mNetTask != null && !mNetTask.isCancelled()) {
            mNetTask.cancel(true);
        }
        mJsonParser = new SpecialListParser();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put(RequestParams.PAGE, "1");
        params.put(RequestParams.PER_PAGE, "20");
        mNetTask = new NetConnectTask(this, mDataParserListener, mJsonParser, RequestUrl.SPECIAL_LIST, params);
        TaskExecute.executeBoolean(mNetTask);
    }

    @SuppressWarnings("unchecked")
    private NetConnectTask.NetDataParseListener mDataParserListener = new NetConnectTask.NetDataParseListener() {

        @Override
        public void onParse(boolean isCancel, String data, int connStatus, Object obj) {
            Log.d(TAG, "data:" + data + ",obj:" + obj);
            if (!isCancel) {
                ErrorData errorData = mJsonParser.getErrorData();

                if (obj != null) {
                    ArrayList<SpecialItem> datas = (ArrayList<SpecialItem>) obj;
                    StringBuilder s = new StringBuilder();
                    for (SpecialItem item : datas) {
                        s.append(item.getSname()).append(": ").append(item.getBanner()).append("\n");
                    }
                    mText.setText(s.toString());
                }
            }
        }
    };
}
